<template>
  <div class="category-manage">
    <!-- 头部区域 -->
    <div class="header">
      <div class="header-left">
        <!-- 返回按钮 -->
        <button class="back-button" @click="goBack">
          <i class="iconfont icon-arrow-left"></i>
        </button>
        <h1 class="title">渠道管理</h1>
        <span class="total">共 {{ total }} 个渠道</span>
      </div>
      <div class="header-right">
        <div class="search-box">
          <input
            v-model="searchKeyword"
            class="search-input"
            placeholder="请输入渠道名称"
            @keyup.enter="handleSearch"
          />
          <button class="search-button" @click="handleSearch">
            <i class="iconfont icon-search"></i>
          </button>
          <button class="clear-button" @click="handleSearchClear">
            <i class="iconfont icon-close"></i>
          </button>
        </div>
        <button class="add-button" @click="showCreatePopup">
          <i class="iconfont icon-add"></i>新增渠道
        </button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 渠道表格 -->
      <div class="table-container">
        <div class="table-header">
          <div class="header-cell" style="width: 40%">渠道名称</div>
          <div class="header-cell" style="width: 20%">排序</div>
          <div class="header-cell" style="width: 20%">状态</div>
          <div class="header-cell" style="width: 20%">操作</div>
        </div>

        <div class="table-body">
          <div v-if="loading" class="loading-mask">
            <div class="loading-spinner"></div>
          </div>

          <div v-if="categoryList.length === 0" class="empty-tips">
            <i class="iconfont icon-box"></i>
            <div class="empty-text">暂无渠道数据</div>
          </div>

          <div
            v-for="item in categoryList"
            :key="item.id"
            class="table-row"
          >
            <div class="table-cell" style="width: 40%">{{ item.name }}</div>
            <div class="table-cell" style="width: 20%">
              {{ item.sort_order || 0 }}
            </div>
            <div class="table-cell" style="width: 20%">
              <span
                class="status-tag"
                :class="item.status === '1' ? 'active' : 'inactive'"
              >
                {{ item.status === '1' ? "启用" : "禁用" }}
              </span>
            </div>
            <div class="table-cell actions" style="width: 20%">
              <button class="action-button edit" @click="showEditPopup(item)">
                <i class="iconfont icon-edit"></i>
              </button>
              <button class="action-button delete" @click="showDeleteConfirm(item.id)">
                <i class="iconfont icon-delete"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <button
          class="page-button"
          :disabled="currentPage === 1"
          @click="currentPage--, getCategoryList()"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
        </span>
        <button
          class="page-button"
          :disabled="currentPage >= totalPages"
          @click="currentPage++, getCategoryList()"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <div
      class="dialog-overlay"
      :class="{ active: showFormPopup }"
      v-if="showFormPopup"
    >
      <!-- 云朵装饰 -->
      <div class="cloud cloud-1"><i class="iconfont icon-cloud"></i></div>
      <div class="cloud cloud-2"><i class="iconfont icon-cloud"></i></div>
      <div class="cloud cloud-3"><i class="iconfont icon-cloud"></i></div>

      <!-- 星星装饰 -->
      <div class="decoration star-1"><i class="iconfont icon-star"></i></div>
      <div class="decoration star-2"><i class="iconfont icon-star"></i></div>
      <div class="decoration star-3"><i class="iconfont icon-star"></i></div>

      <div
        class="dialog-content"
        :class="{ 'bounce-in': showFormPopup }"
      >
        <div class="dialog-header">
          <div class="dialog-title">
            <h2>{{ isEdit ? '编辑渠道' : '新建渠道' }}</h2>
            <div class="title-underline"></div>
          </div>
          <button
            class="close-btn"
            @click="showFormPopup = false"
          >
            <i class="iconfont icon-close"></i>
          </button>
        </div>

        <div class="dialog-body">
          <!-- 渠道名称 -->
          <div class="form-group">
            <label>
              <i class="iconfont icon-name"></i>
              渠道名称
            </label>
            <input
              v-model="formData.name"
              class="form-input"
              placeholder="请输入渠道名称"
            />
          </div>

          <!-- 渠道描述 -->
          <div class="form-group">
            <label>
              <i class="iconfont icon-description"></i>
              渠道描述
            </label>
            <textarea
              v-model="formData.description"
              class="form-input"
              placeholder="请输入渠道描述(可选)"
              rows="3"
            ></textarea>
          </div>

          <div class="form-row">
            <!-- 排序值 -->
            <div class="form-group">
              <label>
                <i class="iconfont icon-sort"></i>
                排序值
              </label>
              <input
                v-model="formData.sort_order"
                type="number"
                class="form-input"
                min="0"
                max="999"
              />
            </div>

            <!-- 状态 -->
            <div class="form-group">
              <label>
                <i class="iconfont icon-status"></i>
                状态
              </label>
              <div class="radio-group">
                <div
                  class="radio-item"
                  :class="{ active: formData.status === '1' }"
                  @click="formData.status = '1'"
                >
                  启用
                </div>
                <div
                  class="radio-item"
                  :class="{ active: formData.status === '0' }"
                  @click="formData.status = '0'"
                >
                  禁用
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="dialog-footer">
          <button
            class="btn cancel-btn"
            @click="showFormPopup = false"
          >
            <i class="iconfont icon-close"></i>取消
          </button>
          <button
            class="btn submit-btn"
            @click="handleSubmit"
            :disabled="loading"
          >
            <i class="iconfont icon-save"></i>{{ isEdit ? '保存修改' : '创建渠道' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div
      class="dialog-overlay"
      :class="{ active: showDeletePopup }"
      v-if="showDeletePopup"
    >
      <!-- 云朵装饰 -->
      <div class="cloud cloud-1"><i class="iconfont icon-cloud"></i></div>
      <div class="cloud cloud-2"><i class="iconfont icon-cloud"></i></div>
      <div class="cloud cloud-3"><i class="iconfont icon-cloud"></i></div>

      <!-- 星星装饰 -->
      <div class="decoration star-1"><i class="iconfont icon-star"></i></div>
      <div class="decoration star-2"><i class="iconfont icon-star"></i></div>
      <div class="decoration star-3"><i class="iconfont icon-star"></i></div>

      <div
        class="dialog-content"
        :class="{ 'bounce-in': showDeletePopup }"
      >
        <div class="dialog-header">
          <div class="dialog-title">
            <h2>确认删除</h2>
            <div class="title-underline"></div>
          </div>
          <button
            class="close-btn"
            @click="showDeletePopup = false"
          >
            <i class="iconfont icon-close"></i>
          </button>
        </div>

        <div class="dialog-body">
          <div class="confirm-message">
            <i class="iconfont icon-warning"></i>
            <p>确定要删除该渠道吗？删除后不可恢复！</p>
          </div>
        </div>

        <div class="dialog-footer">
          <button
            class="btn cancel-btn"
            @click="showDeletePopup = false"
          >
            <i class="iconfont icon-close"></i>取消
          </button>
          <button
            class="btn delete-btn"
            @click="handleDelete"
          >
            <i class="iconfont icon-delete"></i>确定删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { get, post } from "@/request";
import { vToast } from "@/plugins/vToast";

const router = useRouter();

// 数据状态
const categoryList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKeyword = ref("");
const loading = ref(false);

// 表单状态
const showFormPopup = ref(false);
const isEdit = ref(false);
const formData = ref({
  id: "",
  name: "",
  description: "",
  sort_order: 0,
  status: "1",
});

// 删除确认状态
const showDeletePopup = ref(false);
const deletingId = ref("");

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value));

// 返回方法
const goBack = () => {
  router.go(-1);
};

// 方法
const getCategoryList = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
    };

    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }

    const res = await get("/source/list", params);
    if (res && res.code === 200) {
      categoryList.value = res.data?.list || res.data || [];
      total.value = res.data?.pagination?.total || 0;
    }
  } catch (error) {
    console.error("获取渠道列表失败:", error);
    vToast({ message: "获取渠道列表失败" });
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  currentPage.value = 1;
  getCategoryList();
};

const handleSearchClear = () => {
  searchKeyword.value = "";
  currentPage.value = 1;
  getCategoryList();
};

const showCreatePopup = () => {
  isEdit.value = false;
  formData.value = {
    id: "",
    name: "",
    description: "",
    sort_order: 0,
    status: "1",
  };
  showFormPopup.value = true;
};

const showEditPopup = (item) => {
  isEdit.value = true;
  formData.value = {
    id: item.id,
    name: item.name,
    description: item.description,
    sort_order: item.sort_order,
    status: item.status,
  };
  showFormPopup.value = true;
};

const showDeleteConfirm = (id) => {
  deletingId.value = id;
  showDeletePopup.value = true;
};

const handleSubmit = async () => {
  if (!formData.value.name) {
    vToast({ message: "请输入渠道名称" });
    return;
  }

  loading.value = true;

  try {
    const api = isEdit.value ? "/source/update" : "/source/create";
    const successMsg = isEdit.value ? "修改成功" : "创建成功";

    const res = await post(api, formData.value);
    if (res && res.code === 200) {
      vToast({ message: successMsg });
      showFormPopup.value = false;
      getCategoryList();
    }
  } catch (error) {
    console.error("提交渠道失败:", error);
    vToast({ message: "提交渠道失败" });
  } finally {
    loading.value = false;
  }
};

const handleDelete = async () => {
  try {
    const res = await post("/source/delete", { id: deletingId.value });
    if (res && res.code === 200) {
      vToast({ message: "删除成功" });
      showDeletePopup.value = false;
      getCategoryList();
    }
  } catch (error) {
    console.error("删除渠道失败:", error);
    vToast({ message: "删除渠道失败" });
  }
};

// 生命周期
onMounted(() => {
  getCategoryList();
});
</script>

<style scoped lang="less">
.category-manage {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);

  .header-left {
    display: flex;
    align-items: center;

    /* 返回按钮样式 */
    .back-button {
      width: 32px;
      height: 32px;
      margin-right: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: none;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        border-color: var(--bs-theme-color);
        color: var(--bs-theme-color);
      }
      
      .iconfont {
        font-size: 14px;
      }
    }

    .title {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
      color: #303133;
    }

    .total {
      margin-left: 15px;
      font-size: 14px;
      color: #909399;
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 15px;

    .search-box {
      display: flex;
      align-items: center;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      overflow: hidden;

      .search-input {
        width: 250px;
        height: 36px;
        padding: 0 12px;
        border: none;
        outline: none;
        font-size: 14px;
        color: #606266;

        &:focus {
          border-color: var(--bs-theme-color);
        }
      }

      .search-button,
      .clear-button {
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f7fa;
        border: none;
        cursor: pointer;
        color: #909399;

        &:hover {
          color: var(--bs-theme-color);
        }
      }
    }

    .add-button {
      height: 36px;
      padding: 0 15px;
      display: flex;
      align-items: center;
      background-color: var(--bs-theme-color);
      color: #fff;
      border: none;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;
      transition: background-color 0.3s;

      &:hover {
        background-color: #66b1ff;
      }

      .iconfont {
        margin-right: 5px;
        font-size: 14px;
      }
    }
  }
}

.main-content {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.table-container {
  width: 100%;
}

.table-header {
  display: flex;
  background-color: #f5f5f5;
  font-weight: 500;
  color: #606266;
  border-bottom: 1px solid #eee;
}

.header-cell {
  padding: 12px;
  text-align: left;
}

.table-body {
  position: relative;
  min-height: 200px;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #eee;

  &:last-child {
    border-bottom: none;
  }
}

.table-cell {
  padding: 12px;
  color: #606266;
}

.actions {
  display: flex;
  gap: 10px;
}

.action-button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;

  &.edit {
    background-color: #ecf5ff;
    color: var(--bs-theme-color);

    &:hover {
      background-color: #d9ecff;
    }
  }

  &.delete {
    background-color: #fef0f0;
    color: #f56c6c;

    &:hover {
      background-color: #fde2e2;
    }
  }
}

.status-tag {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;

  &.active {
    background-color: #f0f9eb;
    color: #67c23a;
  }

  &.inactive {
    background-color: #fef0f0;
    color: #f56c6c;
  }
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid var(--bs-theme-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-tips {
  padding: 40px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;

  .iconfont {
    font-size: 40px;
    margin-bottom: 10px;
  }

  .empty-text {
    font-size: 14px;
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.page-button {
  height: 32px;
  padding: 0 15px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;

  &:hover:not(:disabled) {
    color: var(--bs-theme-color);
    border-color: #c6e2ff;
    background-color: #ecf5ff;
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.page-info {
  font-size: 14px;
  color: #606266;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99999;
  overflow: hidden;
  transition: background-color 0.3s ease-out;

  &.active {
    background-color: rgba(0, 0, 0, 0.45);
  }

  /* 云朵装饰 */
  .cloud {
    position: absolute;
    font-size: 80px;
    opacity: 0;
    animation: float 8s infinite ease-in-out;
    z-index: -1;
    transition: opacity 0.5s ease;
    color: white;

    &.cloud-1 {
      top: 20%;
      left: 10%;
      animation-delay: 0s;
    }
    &.cloud-2 {
      top: 60%;
      right: 15%;
      animation-delay: 1s;
    }
    &.cloud-3 {
      bottom: 10%;
      left: 25%;
      animation-delay: 2s;
    }
  }

  &.active .cloud {
    opacity: 0.1;
  }

  /* 星星装饰 */
  .decoration {
    position: absolute;
    font-size: 18px;
    animation: float 6s infinite ease-in-out;
    z-index: -1;
    color: var(--bs-theme-color);
    opacity: 0;

    &.star-1 {
      top: 15%;
      right: 15%;
      animation-delay: 0.5s;
    }
    &.star-2 {
      top: 70%;
      left: 15%;
      animation-delay: 1s;
    }
    &.star-3 {
      bottom: 15%;
      right: 20%;
      animation-delay: 1.5s;
    }
  }

  &.active .decoration {
    opacity: 0.1;
  }
}

/* 弹窗内容容器 */
.dialog-content {
  width: 500px;
  max-width: 90vw;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  transform: translateY(40px) scale(0.95);
  opacity: 0;
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  z-index: 100000;

  /* 弹入动画 */
  &.bounce-in {
    transform: translateY(0) scale(1);
    opacity: 1;
  }

  /* 弹窗头部 */
  .dialog-header {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: var(--bs-theme-color);
    color: white;
    position: relative;
    z-index: 2;

    .dialog-title {
      h2 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
      }
      
      .title-underline {
        height: 2px;
        width: 40px;
        background: white;
        border-radius: 1px;
        margin-top: 6px;
      }
    }

    .close-btn {
      width: 32px;
      height: 32px;
      border-radius: 16px;
      background: rgba(255, 255, 255, 0.2);
      border: none;
      color: white;
      font-size: 20px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;

      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }
    }
  }

  /* 弹窗主体 */
  .dialog-body {
    padding: 15px;
    position: relative;
    z-index: 2;

    .form-group {
      margin-bottom: 12px;

      label {
        display: flex;
        align-items: center;
        font-size: 13px;
        color: #606266;
        margin-bottom: 6px;

        .iconfont {
          margin-right: 6px;
          font-size: 14px;
        }
      }

      .form-input {
        width: 100%;
        padding: 10px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        font-size: 13px;
        transition: all 0.3s;
        background: white;
        color: #333;

        &:focus {
          outline: none;
          border-color: var(--bs-theme-color);
        }
      }

      textarea.form-input {
        min-height: 80px;
        resize: vertical;
      }
    }

    .form-row {
      display: flex;
      gap: 12px;

      .form-group {
        flex: 1;
      }
    }

    .radio-group {
      display: flex;
      gap: 10px;
      margin-top: 5px;
      
      .radio-item {
        padding: 8px 15px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        background-color: #fff;
        color: #606266;
        font-size: 13px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 6px;
        transition: all 0.2s;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        &.active {
          background-color: var(--bs-theme-color);
          color: white;
          border-color: var(--bs-theme-color);
        }
      }
    }

    .confirm-message {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      text-align: center;
      
      .iconfont {
        font-size: 40px;
        color: #e6a23c;
        margin-bottom: 15px;
      }
      
      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  /* 弹窗底部 */
  .dialog-footer {
    padding: 12px 15px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    background: #f5f7fa;
    border-top: 1px solid #dcdfe6;
    position: relative;
    z-index: 2;

    .btn {
      padding: 8px 16px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      font-size: 13px;
      font-weight: 600;
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 6px;
      transition: all 0.2s;

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }

      &.cancel-btn {
        background: white;
        color: #606266;

        &:hover:not(:disabled) {
          background: #f2f6fc;
          transform: translateY(-1px);
        }
      }

      &.submit-btn {
        background: var(--bs-theme-color);
        color: white;
        border-color: var(--bs-theme-color);

        &:hover:not(:disabled) {
          background: #66b1ff;
          transform: translateY(-1px);
        }
      }

      &.delete-btn {
        background: #f56c6c;
        color: white;
        border-color: #f56c6c;

        &:hover:not(:disabled) {
          background: #f78989;
          transform: translateY(-1px);
        }
      }
    }
  }
}

/* 浮动动画 */
@keyframes float {
  0%, 100% { 
    transform: translateY(0) translateX(0) rotate(0deg); 
  }
  25% { 
    transform: translateY(-15px) translateX(5px) rotate(2deg); 
  }
  50% { 
    transform: translateY(0) translateX(10px) rotate(0deg); 
  }
  75% { 
    transform: translateY(-10px) translateX(-5px) rotate(-2deg); 
  }
}

/* 响应式设计 */
@media (max-width: 600px) {
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;

    .header-right {
      width: 100%;
      flex-direction: column;
      gap: 10px;

      .search-box {
        width: 100%;
        
        .search-input {
          width: 100%;
        }
      }
    }
  }

  .dialog-content {
    width: 90vw;

    .dialog-header {
      padding: 12px;

      .dialog-title h2 {
        font-size: 16px;
      }
    }

    .dialog-body {
      .form-row {
        flex-direction: column;
        gap: 12px;
      }
    }

    .dialog-footer {
      flex-wrap: wrap;
      
      .btn {
        flex: 1;
        min-width: 100px;
        padding: 6px 12px;
        font-size: 12px;
      }
    }
  }
}
</style>